package com.serviceprovider.business.utility;

//~--- JDK imports ------------------------------------------------------------

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import java.text.SimpleDateFormat;

import java.util.Collection;
import java.util.Date;

/**
 * Some utilities function
 * @author mrduongnv@gmail.com
 *
 */
public class AppUtil {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ddMMyyyy");

    public static int[] toInt(String[] arr) {
        int[] ret = new int[arr.length];

        for (int i = 0; i < arr.length; i++) {
            ret[i] = Integer.parseInt(arr[i]);
        }

        return ret;
    }

    /**
     *  When you get a list of parameters, sometimes you need to convert them to a comma separated list
     */
    public static String toCommaSeparatedString(String[] arr) {
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < arr.length; i++) {
            buffer.append(arr[i]);

            if (i < arr.length - 1) {
                buffer.append(",");
            }
        }

        return buffer.toString();
    }

    public static double[] toDouble(String[] arr) {
        double[] ret = new double[arr.length];

        for (int i = 0; i < arr.length; i++) {
            ret[i] = Double.parseDouble(arr[i]);
        }

        return ret;
    }

    public static boolean getBoolean(Object val) {
        return (val != null) && ("true".equals(val) || "1".equals(val));
    }

    public static Integer getInt(Object val) {
        return (val == null)
               ? null
               : new Integer(String.valueOf(val));
    }

    public static Double getDouble(Object val) {
        return (val == null)
               ? null
               : new Double(String.valueOf(val));
    }

    public static String getDefaultOrderName() {
        return SecurityContextUser.getUserName() + "_" + simpleDateFormat.format(new Date());
    }

    public static String getStackTrace(Throwable aThrowable) {
        final Writer      result      = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);

        aThrowable.printStackTrace(printWriter);

        return result.toString();
    }

    public static String getSqlIN(Collection<Integer> ids) {
        StringBuffer buff   = new StringBuffer("-1");
        String       concat = ",";

        for (Integer id : ids) {
            buff.append(concat).append(id);
        }

        return buff.toString();
    }
}



